package com.mi.proxy5;

import java.lang.reflect.Method;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

public class Test {

	public static void main(String[] args) throws Exception {

		Jay jay = new Jay();
		
		Enhancer enhancer = new Enhancer();
		//Enhancer他是cglib的配置对象，把需要生成的动态字节码类所要继承的基类配置在里面
		enhancer.setSuperclass(jay.getClass());
		enhancer.setCallback(new MethodInterceptor() {
			
			@Override
			public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
				if(method.getName().equals("sign")){
					System.out.println("方文山代理周杰伦签约华裔兄弟");
					return null;
				}else if(method.getName().equals("sing")){
					System.out.println("大家好，周杰伦，请大家多多支持！");
					Object value = method.invoke(jay, args);
					System.out.println("谢谢大家！");
					return value;
				}else if(method.getName().equals("lives")){
					try {
						return method.invoke(jay, args);
					} catch (Exception e) {
						System.out.println("好好生活嘛，父亲之间不要有隔夜仇！");
						throw e;
					}
				}else {
					return method.invoke(jay, args);
				}
			}
		});
		
		Object proxy = enhancer.create();
		System.out.println(proxy.getClass());
		System.out.println(proxy.getClass().getSuperclass());
		Jay jayProxy = (Jay)proxy;
		jayProxy.sing("小苹果");
		jayProxy.sign();
		jayProxy.work();
		int index = jayProxy.lives();
		System.out.println(index);
	}

}
